

package com.netcracker.ui.command;

import com.netcracker.entity.Author;
import com.netcracker.entity.Book;
import com.netcracker.util.service.AuthorService;
import com.netcracker.util.service.BookService;
import com.netcracker.util.service.ServiceFacade;
import com.netcracker.util.service.exception.DataTransmittingException;
import com.netcracker.util.service.exception.NullDataException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;

public class SearchCommand implements Command {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(SearchCommand.class);
    private final ServiceFacade serviceFacade;

        public SearchCommand(ServiceFacade serviceFacade) {
        this.serviceFacade = serviceFacade;
    }

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
        List<Book> books = new ArrayList<>();
        List<Author> authors = new ArrayList<>();
        if (request.getParameter("search") != null && !request.getParameter("search").isEmpty()) {
            String search = request.getParameter("search");
            BookService bookService = serviceFacade.getBookService();
            AuthorService authorService = serviceFacade.getAuthorService();
            try {
                List<Book> booksByAuthor = bookService.findBooksByAuthor(search);
                List<Book> booksByName = bookService.findBooksByName(search);
                books.addAll(booksByAuthor);
                books.addAll(booksByName);
                
                List<Author> authorsByName = authorService.findAuthorsByName(search);
                authors.addAll(authorsByName);
            } catch (NullDataException ex) {
                 request.setAttribute("error", "Книг не найдено.");
            } catch (DataTransmittingException ex) {
                request.setAttribute("error", "Ошибка обращения к БД.");
                LOGGER.error("DB error: ", ex);
                return "index.jsp";
            }
            request.setAttribute("authors", authors);
            request.setAttribute("books", books);
            return "ResultsFound.jsp";  
        } else {
            request.setAttribute("error", "Задайте шаблон поиска.");
            return "ResultsFound.jsp";
        }
    }
    
}
